/*
 *  Copyright (c) 2014 ZengYajian
 *
 *  Simple wrapper for read/write files.
 *  by ZengYajian
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#include "iolib.h"
#include "log/log.h"


struct io_handler *io_file_init(const char *path, int mod)
{
	struct io_handler *h;

	h = malloc(sizeof(*h));
	if (!h) {
		_log(ERROR, "malloc error, file '%s', line '%d'\n", __FILE__, __LINE__);
		return NULL;
	}

	h->file_fd = open(path, mod);
	if (h->file_fd == -1) {
		_log(ERROR, "failed to open file '%s'\n", path);
		free(h);
		return NULL;
	}

	h->file_size = (long)lseek(h->file_fd, (off_t)0, SEEK_END);
	(void)lseek(h->file_fd, (off_t)0, SEEK_SET);

	return h;
}

int io_file_read(struct io_handler *h, char *buffer, int len)
{
	return read(h->file_fd, buffer, len);
}

void io_file_destroy(struct io_handler *h)
{
	free(h);
}


